<template>
  <div class="app-container">
    <div
      v-show="
        !showModify.visible &&
        !showDetails &&
        !detailDialog &&
        !detailsInfo.visible
      "
    >
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-mainCode>
            <el-input
              ref="codeInput"
              v-model="filterInfo.query.queryMap.mainCode.value"
              :clearable="true"
              placeholder="请扫主码或输入主码"
              style="width: 100%"
              @keyup.enter="search"
              @input="(e) => (code = validSe(e))"
            />
          </template>
          <template v-slot:filter-price>
            <div class="price-range">
              <el-input-number
                ref="codeInput"
                v-model="priceRange.left"
                placeholder="请输入供应商价格上限"
                @keyup.enter="search"
                controls-position="right"
                :precision="systemConfig.price_precision"
                @change="setPriceRange('left', priceRange.left)"
              />
              <span> ~ </span>
              <el-input-number
                ref="codeInput"
                v-model="priceRange.right"
                placeholder="请输入供应商价格下限"
                @keyup.enter="search"
                controls-position="right"
                :precision="systemConfig.price_precision"
                @change="setPriceRange('right', priceRange.right)"
              />
            </div>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-uploadProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-uploadNetworkProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.actionNetwork"
            >
              <el-button>导入挂网信息模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-mergeUploadProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.actionMerge"
            >
              <el-button>合并导入模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-updateByExcel>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.actionByExcel"
            >
              <el-button>导入更新模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-showExportExcel>
            <el-button @click="showExportExcel">导出excel</el-button>
          </template>
          <template v-slot:filter-button>
            <el-button
              v-if="$permission('product:enabled')"
              :disabled="
                !tableInfo.selections.length ||
                !!tableInfo.selections.filter((item) => item.status === 1)
                  .length
              "
              style="margin-right: 10px"
              @click="batchEnableProduct('enabled')"
              >启用</el-button
            >
            <el-button
              v-if="$permission('product:enabled')"
              :disabled="
                !tableInfo.selections.length ||
                !!tableInfo.selections.filter((item) => item.status === 0)
                  .length
              "
              @click="batchDisableProduct('disabled')"
              >停用</el-button
            >
            <el-button
              v-if="$permission('product:putDownShelf')"
              :disabled="
                !tableInfo.selections.length ||
                !!tableInfo.selections.filter(
                  (item) => item.putShelfStatus === 1
                ).length
              "
              style="margin-right: 10px"
              @click="batchPutShelfProduct('putShelf')"
              >上架</el-button
            >
            <el-button
              v-if="$permission('product:putDownShelf')"
              :disabled="
                !tableInfo.selections.length ||
                !!tableInfo.selections.filter(
                  (item) => item.putShelfStatus === 0
                ).length
              "
              @click="batchDownShelfProduct('downShelf')"
              >下架</el-button
            >
            <el-button
              :disabled="!tableInfo.selections.length"
              @click="printProductCode()"
              >打印产品码</el-button
            >
            <el-button
              v-if="$permission('product:upload')"
              style="marginleft: 10px"
              @click="uploadImg"
              >上传附件</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        ref="TableContainer"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
      >
        <template v-slot:col-licenseNumber="scope">
          <span
            v-if="
              $permission('productLicense:details') && scope.row.licenseNumber
            "
            class="slip-edit"
            @click="showLicenseDetail(scope.row.licenseId, scope.row)"
          >
            {{ scope.row.licenseNumber }}
          </span>
          <span v-else>{{ scope.row.licenseNumber || '-' }}</span>
        </template>
        <template v-slot:col-commonName="scope">
          <span
            v-if="scope.row.commonName"
            class="slip-edit"
            @click="showDetail(scope.row)"
          >
            {{ scope.row.commonName }}
          </span>
          <span v-else>
            {{ '-' }}
          </span>
        </template>
      </TableContainer>
    </div>
    <product-modify
      v-if="showModify.visible"
      :detailId="detailId"
      v-model:visible="showModify.visible"
      :title="showModify.title"
      :type="showModify.type"
      :isCopy="showModify.isCopy"
      @returnModify="returnModify"
    ></product-modify>
    <product-details
      v-if="detailDialog"
      :id="detailId"
      v-model:visible="detailDialog"
      @returnBack="getList"
      @toggleBrandDetail="toggleShow"
    />
    <license-details
      v-if="showDetails"
      :id="licenseId"
      v-model:visible="showDetails"
      @returnBack="getList"
    ></license-details>
    <BrandDetail
      v-if="detailsInfo.visible"
      :id="detailsInfo.id"
      v-model:visible="detailsInfo.visible"
      @returnBack="brandDetailReturn"
    ></BrandDetail>
    <ChosePrinter
      v-model:visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
    <div v-show="dialogInfo.visible">
      <PageDialog
        :title="dialogInfo.title"
        v-model:visible="dialogInfo.visible"
        :width="dialogInfo.width"
        :bt-loading="dialogInfo.btLoading"
        :bt-list="dialogInfo.btList"
      >
        <div class="asset-msg">
          <div class="asset-msg-label">
            <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
          </div>
          <el-radio-group v-model="dialogInfo.flag">
            <el-radio :label="true">当前页数据</el-radio>
            <el-radio :label="false">全部页数据</el-radio>
          </el-radio-group>
        </div>
      </PageDialog>
    </div>
    <defaultSetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    >
      <template v-slot:preference-mainCode="scope">
        <el-input
          ref="codeInput"
          v-model="scope.row.searchDefaultValue"
          :clearable="true"
          placeholder="请扫主码或输入主码"
          style="width: 100%"
          @input="(e) => (code = validSe(e))"
        />
      </template>
      <template v-slot:preference-price="scope">
        <div class="price-range">
          <el-input-number
            ref="codeInput"
            v-model="priceRange.preferenceLeft"
            placeholder="请输入供应商价格上限"
            controls-position="right"
            :precision="systemConfig.price_precision"
            @change="
              setPrefencePriceRange(
                'preferenceLeft',
                priceRange.preferenceLeft,
                scope.row
              )
            "
          />
          <span> ~ </span>
          <el-input-number
            ref="codeInput"
            v-model="priceRange.preferenceRight"
            placeholder="请输入供应商价格下限"
            controls-position="right"
            :precision="systemConfig.price_precision"
            @change="
              setPrefencePriceRange(
                'preferenceRight',
                priceRange.preferenceRight,
                scope.row
              )
            "
          />
        </div>
      </template>
    </defaultSetPreference>
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <DialogUpload
      v-if="dialogUploadInfo.visible"
      v-model:show-dialog="dialogUploadInfo.visible"
      :isVaildate="false"
      :api="dialogUploadInfo.api"
      :fileType="['png', 'jpg', 'jpeg', 'pdf']"
      :rulesText="'上传规则：以产品编码作为附件名称，同一产品上传多个附件，用产品编码+@#1，产品编码+@#2，同一产品编码数字依次叠加\n例：产品编码a.png，产品编码a@#1.png，产品编码a@#2.pdf\n\xa0\xa0\xa0\xa0\xa0\xa0\xa0产品编码b.png，产品编码b@#1.png，产品编码b@#2.pdf'"
      @callback="getList"
    />
  </div>
</template>

<script setup name="product">
import ProductDetails from './details'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import {
  getProductsPage,
  disableProduct,
  enableProduct,
  putShelfProduct,
  downShelfProduct,
  productCodePrint,
  productsExcel,
  productsFile,
} from '@/api/core'
import { exportTemplateExcel } from '@/api/pub.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import defaultSetPreference from '@/components/SetPreference/defaultSetPreference'
import LicenseDetails from './../license/details'
import ProductModify from '@/views/product/product/modify'
import BrandDetail from '@/views/base/brand/details'
import _ from 'lodash'
const store = useStore()
const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/core/products/import/excel',
  actionNetwork:
    axios.defaults.baseURL + '/core/products/import/networkInformationExcel',
  actionMerge:
    axios.defaults.baseURL + '/core/products/import/mergeUploadExcel',
  actionByExcel:
    axios.defaults.baseURL + '/core/products/import/productUpdateExcel',
  headers: {
    Authorization: store.state.user.token,
  },
  loading: {},
})
const dialogUploadInfo = ref({
  visible: false,
  api: productsFile,
})

// 相关列表
const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  defaultQueryMap: {
    price: {
      queryType: 'BETWEEN',
      value: undefined,
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('product:add'),
    },
    { type: 'slot', value: 'button' },
    {
      type: 'slot',
      value: 'uploadProduct',
      show: proxy.$permission('product:uploadProduct'),
    },
    {
      type: 'slot',
      value: 'updateByExcel',
      show: proxy.$permission('product:updateByExcel'),
    },
    {
      type: 'slot',
      value: 'uploadNetworkProduct',
      // show: proxy.$permission('product:uploadProduct'),
    },
    {
      type: 'slot',
      value: 'mergeUploadProduct',
      show: proxy.$permission('product:mergeImportExcel'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    {
      type: 'button',
      label: '下载合并模板',
      event: mergeDownloadTemplate,
      show: proxy.$permission('product:mergeDownloadTemplate'),
    },
    {
      type: 'button',
      label: '下载导入更新模板',
      event: downloadUpdateExcelTemplate,
      show: proxy.$permission('product:downloadUpdateExcelTemplate'),
    },
    {
      type: 'button',
      label: '下载挂网信息模板',
      event: downloadTemplateNetwork,
    },
    { type: 'slot', label: '导出excel', value: 'showExportExcel' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('product:update'),
      },
      {
        label: '复制并新增',
        event: copyToadd,
        show: proxy.$permission('product:copyToadd'),
      },

      {
        label: proxy.$t('enabled'),
        event: enabled,
        show: proxy.$permission('product:enabled'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: proxy.$t('disabled'),
        event: disabled,
        show: proxy.$permission('product:enabled'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '上架',
        event: putShelf,
        show: proxy.$permission('product:putDownShelf'),
        ifRender(row) {
          return row.putShelfStatus === 0
        },
      },
      {
        label: '下架',
        event: downShelf,
        show: proxy.$permission('product:putDownShelf'),
        ifRender(row) {
          return row.putShelfStatus === 1
        },
      },
      {
        label: '打印产品码',
        event: printProductCode,
        show: true,
      },
    ],
  },
})
const detailDialog = ref(false)
const detailId = ref('')
const showDetails = ref(false)
const paramsFlag = ref(true)
const systemConfig = ref(store.state.permission.systemConfig)
const licenseId = ref('')
const showModify = ref({
  title: '',
  type: 'creat',
  visible: false,
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const priceRange = ref({
  left: undefined,
  right: undefined,
  preferenceLeft: undefined,
  preferenceRight: undefined,
})
const detailsInfo = ref({
  visible: false,
  id: '',
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  msg: '请选择数据导出范围',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: exportExcel,
      show: true,
    },
  ],
})
//由pageInfo更新
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'product' && el.url === val.url) {
                detailDialog.value = false
                showModify.value.visible = false
                showDetails.value = false
                detailsInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailDialog.value = true
                    detailId.value = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

let obj = ref({
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'enabled_type',
    show: false,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  licenseNumber: {
    label: '证号',
    value: 'licenseNumber',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  mainCode: {
    label: '产品属性-原厂主码',
    value: 'mainCode',
    slot: true,
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    componentType: 'price',
    type: 'column',
    slot: true,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
watch(
  () => tableInfo.value.data,
  (val) => {
    const params = proxy.$route.params
    if (params && params.productId && paramsFlag.value) {
      const item = _.find(tableInfo.value.data, ['productId', params.productId])
      sessionStorage.setItem('storeRowId', item.id)
      paramsFlag.value = false
    }
  }
)
function uploadImg() {
  dialogUploadInfo.value.visible = true
}

function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function setPreferenceCallback(obj) {
  let vo = proxy.$fn.deepClone(obj.customizeUserVO)
  updateUserCustomize(vo).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      fieldName: 'type',
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  proxy.$nextTick(() => {
    getList()
  })
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  priceRange.value = {
    left: undefined,
    right: undefined,
    preferenceLeft: undefined,
    preferenceRight: undefined,
  }

  search()
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'productProductList-com.slip.spd.entity.vo.core.CoreProductVONew',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      proxy.$nextTick(() => {
        let data = res.data
        filterInfo.value.query.customizeUserVO = data
        _tableInfo.fieldList = proxy.$fn.setFieldList(
          _tableInfo.fieldList,
          data.detail
        )
        let searchInfo = proxy.$fn.setSearchList(
          _filterInfo.searchList,
          data.detail
        )
        let queryMap = {
          type: {
            queryType: 'EQUALS',
            value: 0,
          },
        }
        _filterInfo.query.queryMap = {
          ..._filterInfo.defaultQueryMap,
          ...searchInfo.queryMap,
          ...queryMap,
        }

        _filterInfo.searchList = searchInfo.searchList
        _filterInfo.searchList.forEach((item) => {
          item.event = search
          if (item.componentType === 'price' && item.searchDefaultValue) {
            let priceArr = proxy.$fn.splitArr(item.searchDefaultValue)
            priceRange.value = {
              left: priceArr[0],
              right: priceArr[1] || undefined,
              preferenceLeft: priceArr[0],
              preferenceRight: priceArr[1] || undefined,
            }
          } else if (
            item.componentType === 'price' &&
            !item.searchDefaultValue
          ) {
            priceRange.value = {
              left: undefined,
              right: undefined,
              preferenceLeft: undefined,
              preferenceRight: undefined,
            }
          }
        })
        _filterInfo.copyQueryMap = proxy.$fn.deepClone(
          _filterInfo.query.queryMap
        )
        slipSelectRequest.value = _slipSelectRequest
        _tableInfo.api = getProductsPage
        getList()
      })
    }
  })
}
function pageInfo(obj) {
  page.value = obj
}
function handleClose() {
  dialogInfo.value.visible = false
}
function exportExcel() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  productsExcel(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
  dialogInfo.value.visible = false
}
function showExportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.flag = true
}
function returnModify() {
  if (detailId.value) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  proxy.$nextTick(() => {
    tableInfo.value.refresh = Math.random()
  })
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailId.value = row.id
  detailDialog.value = true
}
function search() {
  const _tableInfo = tableInfo.value
  advancedSearchInfo.value.data = {}
  if (priceRange.value.left && priceRange.value.right) {
    filterInfo.value.query.queryMap.price.value =
      priceRange.value.left + ',' + priceRange.value.right
  }

  filterInfo.value.query.queryDtoList = []
  _tableInfo.initCurpage = Math.random()
  _tableInfo.refresh = Math.random()
}
function copyToadd(row) {
  showModify.value.visible = true
  showModify.value.type = 'create'
  showModify.value.isCopy = true
  showModify.value.title = '复制并新增'
  detailId.value = row.productId
}

function create() {
  showModify.value.type = 'create'
  showModify.value.title = '新增产品'
  showModify.value.visible = true
  showModify.value.isCopy = false
  detailId.value = ''
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  showModify.value.type = 'update'
  showModify.value.title = '修改产品'
  showModify.value.visible = true
  showModify.value.isCopy = false
  detailId.value = row.productId
  // 显示信息
}
function enabled(row) {
  const ids = getIds(row)
  enableProduct(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disabled(row) {
  proxy
    .$prompt('请输入停用理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.isNotEmptyString,
      inputErrorMessage: '请输入停用理由并不超过200字符',
    })
    .then(({ value }) => {
      const ids = getIds(row)
      disableProduct({ ids, reason: value }).then((resp) => {
        if (resp) {
          getList()
        }
      })
    })
}
//上架
function putShelf(row) {
  const ids = getIds(row)
  putShelfProduct(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//下架
function downShelf(row) {
  proxy
    .$prompt('请输入下架理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.isNotEmptyString,
      inputErrorMessage: '请输入下架理由并不超过200字符',
    })
    .then(({ value }) => {
      const ids = getIds(row)
      downShelfProduct({ ids, reason: value }).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function getIds(row) {
  if (row && row.id) {
    return [row.id]
  } else {
    return tableInfo.value.selections.map((value) => value.id)
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function batchDisableProduct(status, row) {
  proxy
    .$prompt('请输入停用理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.isNotEmptyString,
      inputErrorMessage: '请输入停用理由并不超过200字符',
    })
    .then(({ value }) => {
      const ids = getIds(row)
      disableProduct({ ids, reason: value }).then((resp) => {
        if (resp) {
          getList()
        }
      })
    })
}
function batchEnableProduct(status, row) {
  const ids = getIds(row)
  enableProduct(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function batchPutShelfProduct(status, row) {
  const ids = getIds(row)
  putShelfProduct(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function batchDownShelfProduct(status, row) {
  proxy
    .$prompt('请输入下架理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.isNotEmptyString,
      inputErrorMessage: '请输入下架理由并不超过200字符',
    })
    .then(({ value }) => {
      const ids = getIds(row)
      downShelfProduct({ ids, reason: value }).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function showLicenseDetail(id, row) {
  sessionStorage.setItem('storeRowId', row.id)
  licenseId.value = id
  showDetails.value = true
}
function toggleShow(val) {
  detailDialog.value = false
  detailsInfo.value.id = val
  detailsInfo.value.visible = true
}
function brandDetailReturn() {
  detailDialog.value = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function setPriceRange(type, value) {
  if (
    (priceRange.value.left &&
      priceRange.value.right &&
      parseFloat(priceRange.value.left) > parseFloat(priceRange.value.right)) ||
    parseFloat(value) < 0
  ) {
    priceRange.value[type] = undefined
  }
}
function setPrefencePriceRange(type, value, row) {
  proxy.$nextTick(() => {
    if (
      (priceRange.value.preferenceRight &&
        priceRange.value.preferenceLeft &&
        parseFloat(priceRange.value.preferenceLeft) >
          parseFloat(priceRange.value.preferenceRight)) ||
      parseFloat(value) < 0
    ) {
      priceRange.value[type] = undefined
      row.searchDefaultValue = undefined
    } else if (
      !priceRange.value.preferenceLeft &&
      !priceRange.value.preferenceRight
    ) {
      priceRange.value[type] = undefined
      row.searchDefaultValue = undefined
    } else {
      row.searchDefaultValue =
        priceRange.value.preferenceLeft + ',' + priceRange.value.preferenceRight
    }
  })
}
function downloadTemplate() {
  exportTemplateExcel('product_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function downloadTemplateNetwork() {
  exportTemplateExcel('network_product_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function downloadUpdateExcelTemplate() {
  exportTemplateExcel('product_update_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function mergeDownloadTemplate() {
  exportTemplateExcel('product_merge_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function printProductCode(row) {
  let data = []
  if (row && row.id) {
    data.push(row.id)
  } else {
    data = tableInfo.value.selections.map((item) => item.id)
  }
  if (data.length) {
    productCodePrint(data).then((res) => {
      if (res && res.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = res.data
      }
    })
  } else {
    proxy.$message({
      message: '选择需要打印的二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}

getCustomize()
</script>

<style scoped lang="scss">
:deep(.box-scroll-y) {
  height: calc(100% - 40px);
}
.price-range {
  display: flex;
  align-items: center;
}
</style>
